<!--
* @author: Charles_XDXD
* @description: 视频播放历史记录
-->
<template>
  <div style="padding: 24px; background-color: white">
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
      "
    >
      <a-input-search
        v-model:value="searchQuery.title"
        placeholder="按标题查找视频"
        enter-button
        @search="handleSearch"
        style="max-width: 300px"
      />

      <a-button
        @click="clearRecord"
        danger
      >
        一键清空历史记录
      </a-button>
    </div>

    <div v-if="historyRecordList.length > 0">
      <a-row :gutter="[16, 16]">
        <a-col
          :span="6"
          v-for="(history, index) in historyRecordList"
          :key="index"
        >
          <a-card style="height: 100%">
            <template #cover>
              <img
                alt="视频封面"
                :src="history.thumbnailUrl"
                style="
                  padding: 20px;
                  width: 100%;
                  height: 180px;
                  object-fit: cover;
                  cursor: pointer;
                  border-radius: 10%;
                "
                @click="locateToVideoPage(history.videoId)"
              />
            </template>

            <a-card-meta>
              <template #title>
                <div
                  class="card-title"
                  :title="history.title"
                  @click="locateToVideoPage(history.videoId)"
                >
                  {{ history.title }}
                </div>
              </template>

              <template #description>
                <div
                  class="card-author"
                  @click="locateToUserProfile(history.userId)"
                >
                  <img
                    :src="history.avatarUrl"
                    class="avatar"
                    alt="作者头像"
                  />
                  <span class="card-author-name">{{ history.nickname }}</span>
                </div>

                <div class="card-details">
                  <a-tag
                    :color="getStatusInfo(history.playStatus).color"
                    style="margin-bottom: 8px; text-align: center"
                  >
                    {{ getStatusInfo(history.playStatus).label }}
                  </a-tag>
                  <div class="progress-container">
                    <div
                      class="progress-bar"
                      :style="{ width: getProgress(history) }"
                    ></div>
                  </div>
                  <span>播放量: {{ formatNumber(history.viewCount) }}</span>
                  <span>发布时间: {{ formatTime(history.publishTime) }}</span>
                  <span>最后观看: {{ formatTime(history.updateTime) }}</span>
                </div>

                <div class="action-buttons">
                  <a-button
                    type="primary"
                    danger
                    @click="deleteRecord(history.videoId)"
                  >
                    删除
                  </a-button>
                </div>
              </template>
            </a-card-meta>
          </a-card>
        </a-col>
      </a-row>

      <Pagination
        style="margin-top: 20px"
        v-model:page="searchQuery.pageNo"
        v-model:limit="searchQuery.pageSize"
        :total="total"
        @pagination="getPage"
      />
    </div>
    <div v-else>
      <a-empty />
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import type { CvVideoHistorySearchReqVO, CvVideoHistoryRespVO } from '@/types/history'
import {
  clearVideoHistoryRecord,
  deleteVideoHistoryRecord,
  getVideoHistoryRecordPage
} from '@/api/history'
import { videoPlayStatus } from '@/utils/options'
import { message, Modal } from 'ant-design-vue'

/**
 * 历史记录搜索条件
 */
const searchQuery = ref<CvVideoHistorySearchReqVO>({
  title: '',
  pageNo: 1,
  pageSize: 10
})

/**
 * 历史记录列表
 */
const historyRecordList = ref<CvVideoHistoryRespVO[]>([])

/**
 * 历史记录列表总数
 */
const total = ref(0)

/**
 * 播放量格式化
 */
const formatNumber = (num: number) => {
  if (!num) {
    return 0
  }

  if (num >= 1000 && num < 10000) {
    return (num / 1000).toFixed(1) + 'K'
  } else if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'W'
  } else {
    return num.toString()
  }
}

/**
 * 时间格式化
 */
const formatTime = (time: string) => {
  if (time) {
    return dayjs(time).format('YYYY-MM-DD HH:mm')
  }
  return ''
}

/**
 * 获取状态信息
 */
const getStatusInfo = (status: string) => {
  return videoPlayStatus.find(item => item.value === status) || { label: '', color: '' }
}

/**
 * 计算播放进度
 */
const getProgress = computed(() => (history: CvVideoHistoryRespVO) => {
  return `${((history.position / history.duration) * 100).toFixed(2)}%`
})

/**
 * 获取历史记录分页数据
 */
const getPage = async () => {
  const res = await getVideoHistoryRecordPage(searchQuery.value)
  historyRecordList.value = res.list
  total.value = res.total
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  searchQuery.value.pageNo = 1
  getPage()
}

/**
 * 删除历史记录
 */
const deleteRecord = (videoId: number) => {
  Modal.confirm({
    title: '确定要删除该历史记录吗？',
    content: '删除后无法恢复',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: async () => {
      await deleteVideoHistoryRecord(videoId)
      await getPage()
      message.success('删除成功')
    }
  })
}

/**
 * 清空历史记录
 */
const clearRecord = async () => {
  Modal.confirm({
    title: '确定要清空历史记录吗？',
    content: '清空后无法恢复',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: async () => {
      await clearVideoHistoryRecord()
      searchQuery.value.pageNo = 1
      await getPage()
      message.success('清空成功')
    }
  })
}

/**
 * 加载历史记录
 */
onMounted(() => {
  getPage()
})

/**
 * 跳转到视频页面
 */
const locateToVideoPage = (videoId: number) => {
  videoId && window.open(`/video?videoId=${videoId}`)
}

/**
 * 跳转到用户个人主页
 */
const locateToUserProfile = (userId: number) => {
  userId && window.open(`/profile?userId=${userId}`)
}
</script>

<style scoped>
h1 {
  margin-bottom: 24px;
}

.card-title {
  font-size: 16px;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-author {
  display: flex;
  align-items: center;
  height: 50px;
  margin-bottom: 8px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 8px;
  cursor: pointer;
}

.card-author-name {
  font-size: 16px;
  color: #555;
  cursor: pointer;
}

.card-details {
  font-size: 12px;
  color: #999;
}

.card-details span {
  display: block;
  margin-top: 4px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.action-buttons button {
  font-size: 15px;
}

.progress-container {
  height: 4px;
  background-color: #f0f0f0;
  border-radius: 2px;
  margin: 8px 0;
}

.progress-bar {
  height: 100%;
  background-color: #1890ff;
  border-radius: 2px;
  transition: width 0.3s;
}
</style>
